class Category < ActiveRecord::Base
  has_many :categories
  belongs_to :category
  has_many :ad_categories
  has_many :ads, :through => :ad_categories
  has_many :auctions, :class_name => "Auction", :finder_sql => 'SELECT auctions.* FROM auctions INNER JOIN ads ON ads.id = auctions.ad_id INNER JOIN ad_categories ON ad_categories.ad_id = auctions.ad_id WHERE ad_categories.category_id = #{id}'

  def unformatted_category_path
    unless (category == nil)
      return category.unformatted_category_path +
        " / " +
        name
    else
      return name
    end
  end

  def to_param
    unformatted_category_path.downcase.gsub(/[åä]+/,'a').gsub(/[ö]+/,'o').gsub(/[^a-z0-9\s_-]+/,'').gsub(/[\s_-]+/,'/') + "/#{id}"
  end

  def recursive_ads(province=nil,county=nil)
    map = Hash.new
    ads.each() { |ad|
      next if ad.enddate.to_formatted_s(:db) < Time.now.to_formatted_s(:db)
      next if (province && ad.user.county.province != province)
      next if (county && ad.user.county != county)
      map[ad.id] = ad
    }

    categories.each { |c|
      map = map.merge(c.recursive_ads(province,county))
    }
    map
  end

  def recursive_ads_desc_end(province=nil,county=nil)
    (recursive_ads(province,county).values).sort { |a,b| a.enddate <=> b.enddate }
  end

  def recursive_ads_count
    map = Hash.new
    ads.each() { |ad|
      map[ad.id] = true
    }
    categories.each { |c|
      map = map.merge(c.recursive_ads)
    }
    map.size
  end

  def recursive_auctions(seconds, max, province=nil, county=nil)
    map = Hash.new
    auctions.each() { |a|
      time_left = (a.ad.enddate-Time.now)
      if (time_left < seconds && time_left > 0)
        map[a.id] = a
      end
      if (map.size > max)
        return map
      end
    }

    categories.each { |c|
      map = map.merge(c.recursive_auctions(seconds, max, province, county))
      if (map.size > max)
        return map
      end
    }
    map
  end

  def self.search(query, limit, province=nil, county=nil)
    if query.length == 0
      return Array.new
    end
    
    Category.find_by_sql("SELECT categories.* FROM categories WHERE categories.name LIKE '%#{query}%' LIMIT #{limit}")
  end
end
